import requests
import socket
import json
import os

#  @author Ryanlu9910@gmail.com
#  @date   2021/4/18

# 获取私网ip
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
local_ip = s.getsockname()[0]

# 学号
student_id = ''
# 密码
student_pw = ''
# 学生信息
student_info = {}
# 保存标志
saved = False
# 请求url
url = 'http://192.168.255.4:801/eportal/?c=ACSetting&a=Login&protocol=http:&hostname=192.168.255.4&iTermType=1&' \
      'wlanuserip={my_ip}&wlanacip=null&wlanacname=null&mac=00-00-00-00-00-00&ip={my_ip}&enAdvert=0' \
      '&queryACIP=0&loginMethod=1'.format(my_ip=local_ip)
# 伪装头
headers = {
    'Host': '192.168.255.4:801',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36',
    # 从表单传输数据
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'Origin': 'http://192.168.255.4',
    'Referer': 'http://192.168.255.4/',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'closed'
}


def login(student_id, student_pw):
    login_data = {
        'DDDDD': student_id,
        'upass': student_pw,
    }
    r = requests.post(url, data=login_data, headers=headers)
    try:
        if requests.get('http://www.baidu.com').status_code == 200:
            print('校园网登录成功')
    except BaseException:
        print("登录失败！重新运行")
        exit()


saved = os.path.exists('./student_file.json')
if (saved):
    with open('./student_file.json', 'r') as f:
        student_info = json.loads(f.read())
        student_id = student_info['DDDDD']
        student_pw = student_info['upass']
        login(student_id, student_pw)
        print("OKK，学习去吧")
else:
    print('请输入学号：')
    student_id = input()
    print('请输入密码：')
    student_pw = input()
    login(student_id, student_pw)

    print("是否保存登录信息？（Y/N）")
    answer = input()
    if (answer == 'Y' or answer == 'y'):
        with open('./student_file.json', 'w') as f:
            student_info['DDDDD'] = student_id
            student_info['upass'] = student_pw
            f.write(json.dumps(student_info))
        print('已保存！')
    else:
        print('下次还需重新登录')
